import {Application, Session} from "mydog";
import {svr_info} from "../../../app/svr_info/svr_info";
import {
    changeConGameState,
    changeInfoGameState,
    GameType,
    randGameSvrByType,
    svrType
} from "../../../app/util/gameUtil";

export default class Handler {
    app: Application;
    constructor(app: Application) {
        this.app = app;
    }

    // 修改昵称
    changeNickname(msg: { nickname: string }, session: Session, next: Function) {
        let role = svr_info.roleMgr.getRole(session.uid);
        role.changeRoleInfo({ "nickname": msg.nickname });
        next({ "code": 0, "nickname": msg.nickname });
    }

    //  进入房间
    enter(msg: {gameType:GameType}, session: Session, next: Function) {
        let role = svr_info.roleMgr.getRole(session.uid);
        if (role.isMatchRpcing) {
            return;
        }
        if (role.role.gameSvr) {
            if (role.role.tableId) {
                return next({ "code": 1, "errmsg": "当前正在游戏中" });
            } else {
                return;
            }
        }

        role.isMatchRpcing = true;
        //随机一个游戏服务
        let gameSvr = randGameSvrByType(msg.gameType);
        if(gameSvr==null){
            return next({ "code": 1, "errmsg": "游戏不存在" });
        }
        this.app.rpc(gameSvr.id).game.main.enter(role.toEnterJson(), (err) => {
            role.isMatchRpcing = false;
            if (err) {
                changeInfoGameState(role.role.uid, { "gameSvr": "","gameType":GameType.NULL, "tableId": 0 });
                return next({ "code": 2, "errmsg": "没有空余的位置" });
            }else{
                return next({ "code": 0,"gameType":gameSvr.gameType});
            }
        });
    }

    // 重连游戏
    relink(msg: any, session: Session, next: Function) {
        let role = svr_info.roleMgr.getRole(session.uid);
        if (!role.role.gameSvr || !role.role.tableId) {
            return next({ "code": 1 , "errmsg": "查无玩家桌子信息"});
        }
        this.app.rpc(role.role.gameSvr).game.main.relink(role.role.tableId, role.uidsid, (err, ok) => {
            if (err) {
                return next({ "code": 2 , "errmsg": "游戏服务器繁忙"});
            }
            if (!ok) {
                changeInfoGameState(session.uid, { "gameSvr": "","gameType":GameType.NULL, "tableId": 0 });
                return next({ "code": 1, "errmsg": "游戏已结束" });
            } else {
                changeConGameState(session.uid, session.sid, { "gameSvr": role.role.gameSvr, "gameType":role.role.gameType,"tableId": role.role.tableId });
                return next({ "code": 0 ,"gameType":role.role.gameType});
            }
        });
    }
}


